package org.restql.webapp;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;

public class AccessControl {

	private static Log logger = LogFactory.getLog(AccessControl.class);

	private String user = "root";
	private String password = "";
	private String tableName;
	private String operation;
	private String dbName;

	public AccessControl(HttpServletRequest request, String dbName, String tableName, String operation, String username, String password) {
		String authHeader = request.getHeader("Authorization");
		logger.info(authHeader);

		
		this.tableName = tableName;
		this.operation = operation;
		this.dbName = dbName;
		// 2009/11/15 restql-continue f.yang
		this.user = username;
		this.password = password;

		// 2009/11/15 restql-continue f.yang
		if (authHeader != null && authHeader.startsWith("Basic ")) {
			String val = new String(Base64.decode(authHeader.substring(6)));
			String []parts = val.split(":");
			this.user = parts[0];
			this.password = parts[1];
		}

	}

	public String getPassword() {
		return password;
	}

	public String getUser() {
		return user;
	}

	public boolean operationAuthorized() {
		logger.info("Authorizing " + operation + " for table: " + dbName + "." + tableName);
		if (dbName.equalsIgnoreCase("mysql")) {
			return false;
		}
		return true;
	}
}
